﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Data;
using System.ComponentModel;
using System.Globalization;


namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para FRMconLiqNom.xaml
    /// </summary>
    public partial class FRMconLiqNom : Window
    {
        
        conLiqNom _conLiqNom;

        public FRMconLiqNom()
        {
            InitializeComponent();
            _conLiqNom = (conLiqNom)this.DataContext;
            conLiqNom.clsConcep.LiqNom = _conLiqNom;            
        }

        private void butGua_Click(object sender, RoutedEventArgs e)
        {
            _conLiqNom.guardar(wPnot);
        }

        private void butSal_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void datCon_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            MessageBox.Show("d");
        }

        private void datCon_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
   
        }

        private void datCon_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            MessageBox.Show("d");
        }

        private void addConcep_Click(object sender, RoutedEventArgs e)
        {
            _conLiqNom.addEmp();

            int index = _conLiqNom.lisConcep.Count - 1;
            datCon.SelectedIndex = index;
            

            if (datCon.SelectedIndex > 1)
            {
                datCon.ScrollIntoView(datCon.Items[datCon.SelectedIndex - 1]);
                datCon.ScrollIntoView(datCon.Items[datCon.SelectedIndex]);
            }

            var dataGridCellInfo = new DataGridCellInfo(datCon.Items[index], datCon.Columns[0]);

            datCon.CurrentCell = dataGridCellInfo;
            datCon.BeginEdit();

        }

        private void delConcep_Click(object sender, RoutedEventArgs e)
        {
            _conLiqNom.delEmp();
        }

        private void datCon_LostFocus(object sender, RoutedEventArgs e)
        {
            Boolean errors = (from c in (from object i in datCon.ItemsSource select datCon.ItemContainerGenerator.ContainerFromItem(i))
                              where c != null
                              select Validation.GetHasError(c)).FirstOrDefault(x => x);

            _conLiqNom.ERROR = errors;
        }

        private void datCon_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) 
            { 
                datCon_LostFocus(null, null);
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (_conLiqNom.CAMBIO)
            {
                if (MessageBox.Show("¿Está seguro que desea salir? se perderan los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void datCon_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        } 

    }

    public class conLiqNom:ObservableObject 
    {

        public conLiqNom()
        {
            MDOgeneral.conectar();
            strTituloVentana = "Conceptos de liquidación de nomina" + " - Usuario: " + MDOgeneral.usuario + " - [FRMconLinqNom]";
        }

        private string _strTituloVentana;
        public string strTituloVentana
        {
            get { return _strTituloVentana; }
            set { _strTituloVentana = value; base.OnPropertyChanged("strTituloVentana"); }
        }

        private string _TIPO="P";
        public string TIPO
        {
            get { return _TIPO; }
            set
            {
                _TIPO = value;
                clsConcep Concep = new clsConcep();
                Concep.CONCEP.TIPO_CPT = _TIPO;
                lisConcep=Concep.listaConcep();
                RaisePropertyChangedEvent("TIPO");
            }
        }

        private ObservableCollection<clsConcep> _lisConcep=new clsConcep().listaConcep();
        public ObservableCollection<clsConcep> lisConcep
        {
            get { return _lisConcep; }
            set { _lisConcep = value; RaisePropertyChangedEvent("lisConcep"); }
        }

        private clsConcep _selConcep = new clsConcep();
        public clsConcep selConcep
        {
            get { return _selConcep; }
            set { _selConcep = value; RaisePropertyChangedEvent("selConcep"); }
        }
        
        private Boolean _CAMBIO = false;
        public Boolean CAMBIO
        {
            get { return _CAMBIO; }
            set { _CAMBIO = value; RaisePropertyChangedEvent("CAMBIO"); }
        }

        private Boolean _ERROR=false;
        public Boolean ERROR
        {
            get { return _ERROR; }
            set { _ERROR = value; RaisePropertyChangedEvent("ERROR"); }
        }

        public class clsConcep : ObservableObject
        {
            public ObservableCollection<clsConcep> listaConcep()
            {
                ObservableCollection<clsConcep> lisConcep = new ObservableCollection<clsConcep>();
                try
                {
                    DataTable val = CONCEP.listaConcep();
                    foreach (DataRow r in val.Rows)
                    {
                        clsConcep Concep = new clsConcep();
                        Concep.CONCEP.TIPO_CPT = r["TIPO_CPT"].ToString().Trim();
                        Concep.CONCEP.CODCPT_CPT = r["CODCPT_CPT"].ToString().Trim();
                        Concep.CONCEP.AFEBAS_CPT = r["AFEBAS_CPT"].ToString().Trim();
                        Concep.CONCEP.NOMCPT_CPT = r["NOMCPT_CPT"].ToString().Trim();
                        Concep.CONCEP.TIPNOV_CPT = r["TIPNOV_CPT"].ToString().Trim();
                        Concep.CONCEP.TIPREP_CPT = r["TIPREP_CPT"].ToString().Trim();
                        Concep.CONCEP.CAMBIO = false;
                        Concep.CONCEP.EXISTE = true;
                        lisConcep.Add(Concep);
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                return lisConcep;
            }

            #region  Propiedades

            private clases.CLSCONCEP _CONCEP = new clases.CLSCONCEP { TIPO_CPT = "P", CODCPT_CPT = "", NOMCPT_CPT = "", TIPREP_CPT = "P", TIPNOV_CPT = "F", AFEBAS_CPT = "N" };
            public clases.CLSCONCEP CONCEP
            {
                get { return _CONCEP; }
                set { _CONCEP = value; RaisePropertyChangedEvent("CONCEP"); }
            }
            
            public string TIPO_CPT
            {
                get { return CONCEP.TIPO_CPT; }
                set { CONCEP.TIPO_CPT = value; RaisePropertyChangedEvent("TIPO_CPT"); }
            }
            public string CODCPT_CPT
            {
                get { return CONCEP.CODCPT_CPT; }
                set { CONCEP.CODCPT_CPT = value; RaisePropertyChangedEvent("CODCPT_CPT"); }
            }
            public string NOMCPT_CPT
            {
                get { return CONCEP.NOMCPT_CPT; }
                set
                {
                    if (CONCEP.NOMCPT_CPT != value) { CAMBIO = true; }
                    CONCEP.NOMCPT_CPT = value;
                    RaisePropertyChangedEvent("NOMCPT_CPT");
                }
            }
            public string TIPREP_CPT
            {
                get { return CONCEP.TIPREP_CPT; }
                set
                {
                    if (CONCEP.TIPREP_CPT != value) { CAMBIO = true; }
                    CONCEP.TIPREP_CPT = value;
                    RaisePropertyChangedEvent("TIPREP_CPT");
                }
            }
            public string TIPNOV_CPT
            {
                get { return CONCEP.TIPNOV_CPT; }
                set
                {
                    if (CONCEP.TIPNOV_CPT != value) { CAMBIO = true; }
                    CONCEP.TIPNOV_CPT = value;
                    RaisePropertyChangedEvent("TIPNOV_CPT");
                }
            }
            public string AFEBAS_CPT
            {
                get { return CONCEP.AFEBAS_CPT; }
                set
                {
                    if (CONCEP.AFEBAS_CPT != value) { CAMBIO = true; }
                    CONCEP.AFEBAS_CPT = value;
                    RaisePropertyChangedEvent("AFEBAS_CPT");
                }
            }

            private Boolean _CAMBIO = false;
            public Boolean CAMBIO
            {
                get { return _CAMBIO; }
                set
                {
                    _CAMBIO = value;
                    CONCEP.CAMBIO = value;
                    LiqNom.CAMBIO = true;
                    RaisePropertyChangedEvent("CAMBIO");
                }
            }

            private Boolean _BORRAR=false;
            public Boolean BORRAR
            {
                get { return _BORRAR; }
                set
                {
                    _BORRAR = value;
                    LiqNom.CAMBIO = true;
                    RaisePropertyChangedEvent("BORRAR");
                }
            }

            private Boolean _NUEVO = false;
            public Boolean NUEVO
            {
                get { return _NUEVO; }
                set
                {
                    _NUEVO = value;
                    LiqNom.CAMBIO = true;
                    RaisePropertyChangedEvent("NUEVO");
                }
            }

            static private conLiqNom _LiqNom;
            static public conLiqNom LiqNom 
            {
                get { return _LiqNom; }
                set { _LiqNom = value; }
            }

            #endregion
        }

        public void addEmp()
        {
            clsConcep Concep = new clsConcep();
            Concep.TIPO_CPT = TIPO;
            Concep.NUEVO = true;
            lisConcep.Add(Concep);
        }

        public void delEmp()
        {
            if (selConcep != null)
            {
                if (selConcep.BORRAR)
                {
                    selConcep.BORRAR = false;
                }
                else
                {
                    selConcep.BORRAR = true;
                    if (selConcep.NUEVO == true)
                    {
                        lisConcep.Remove(selConcep);
                    }
                }
            }
        }


        public void guardar(WrapPanel wPnot)
        {
            if (MessageBox.Show("¿Está seguro que desea guardar los cambios realizados?", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
            {
                return;
            }

            try
            {
                List<clases.CLSCONCEP> lisConcAdd = new List<clases.CLSCONCEP>();
                List<clases.CLSCONCEP> lisConcDel = new List<clases.CLSCONCEP>();
                List<clases.CLSCONCEP> lisConcMod = new List<clases.CLSCONCEP>();

                for (int i = 0; i <= lisConcep.Count - 1; i++)
                {
                    if (lisConcep[i].NUEVO == true)
                    {
                        lisConcAdd.Add(lisConcep[i].CONCEP);
                    }

                    if (lisConcep[i].BORRAR == true)
                    {
                        lisConcDel.Add(lisConcep[i].CONCEP);
                    }

                    if (lisConcep[i].CAMBIO == true && lisConcep[i].NUEVO == false && lisConcep[i].BORRAR == false)
                    {
                        lisConcMod.Add(lisConcep[i].CONCEP);
                    }
                }

                if (new clases.CLSCONCEP().guardar(lisConcAdd,lisConcDel,lisConcMod) > 0)
                {
                    new MDOgeneral.notificar(wPnot, "Los cambios fueros guardados correctamente.", true);
                    clsConcep Concep = new clsConcep {TIPO_CPT=TIPO };
                    lisConcep= Concep.listaConcep();
                    CAMBIO = false;
                }
                else
                {
                    new MDOgeneral.notificar(wPnot, "Los cambios no pueden ser guardados.", false);
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    }

}

namespace ReglasValidacion
{
    //validar equipo produccion
    public class esOKconLiqNom : ValidationRule
    {
        public produccion.forms.conLiqNom conLiqNom { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult res;

            if (String.IsNullOrEmpty(conLiqNom.selConcep.CODCPT_CPT))
            {
                if (!String.IsNullOrEmpty(conLiqNom.selConcep.NOMCPT_CPT))
                {
                    return new ValidationResult(false, "El codigo del concepto no puede estar vacio.");
                }
                return new ValidationResult(true, null);
            }

            if (!conLiqNom.selConcep.CONCEP.EXISTE)
            {
                res = new esOKcadena { Maxc = 3, Minc = 1 }.Validate(conLiqNom.selConcep.CODCPT_CPT, cultureInfo);
                if (!res.IsValid)
                {
                    return new ValidationResult(false, res.ErrorContent.ToString().Replace("campo", "codigo del concepto"));
                }

                if (conLiqNom.selConcep.CONCEP.existe())
                {
                    return new ValidationResult(false, "El codigo del concepto ingresado ya existe.");
                }
                else
                {
                    if (conLiqNom.lisConcep.ToList().FindAll(r => r.CODCPT_CPT.Equals(conLiqNom.selConcep.CODCPT_CPT)).Count > 1)
                    {
                        return new ValidationResult(false, "El codigo del concepto ingresado ya existe.");
                    }
                }
            }

            res = new esOKcadena { Maxc = 20, Minc = 1 }.Validate(conLiqNom.selConcep.NOMCPT_CPT, cultureInfo);
            if (!res.IsValid)
            {
                return new ValidationResult(false, res.ErrorContent.ToString().Replace("campo", "el nombre del concepto"));
            }

            return new ValidationResult(true, null);
        }
    }

}

